package itsm.isperp.framework.sequence.rule;

import java.text.DecimalFormat;

import org.joda.time.DateTime;

/**
 * 序列号规则的构建器
 * 
 * @author lizx
 * @date 2013-3-5
 * @version V1.0
 */
public class SequenceRuleBuilder {

	/**
	 * 获取流水号的前缀
	 * 
	 * @param rule
	 * @return
	 */
	public static final String getPrefix(String rule) {

		// 解析日期及前缀
		int dIndex1 = 0, dIndex2 = 0;
		dIndex1 = rule.indexOf("<%", 0);
		dIndex2 = rule.indexOf("%>", dIndex1 + 1);
		String dateFormat = "", date = "";
		if (dIndex1 > 0 && dIndex2 > 0) {
			dateFormat = rule.substring(dIndex1 + 2, dIndex2);
			date = DateTime.now().toString(dateFormat);
		} else {
			dIndex1 = 0;
			dIndex2 = -2;

		}

		int numIndex1 = rule.indexOf("{");

		// /生成前缀
		String prefix = rule.substring(0, dIndex1) + date
				+ rule.substring(dIndex2 + 2, numIndex1);

		return prefix.replace(" ", "");

	}

	/**
	 * 获取流水号数字化格式方式
	 * 
	 * @param rule
	 * @return
	 */
	public static final String getFormatedNumber(String rule, long number) {
		int numIndex1 = 0, numIndex2 = 0;
		numIndex1 = rule.indexOf("{", 0);
		numIndex2 = rule.indexOf("}", numIndex1 + 1);
		return new DecimalFormat(rule.substring(numIndex1 + 1, numIndex2))
				.format(number);
	}

}
